package com.yuzhitong.shapi;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.SdkConfig;
import com.umeng.commonsdk.UMConfigure;
import com.yuzhitong.shapi.activity.HomeActivity;
import a.a.a.MyApplication;
import com.yuzhitong.shapi.base.BaseMvpActivity;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.contract.StartContract;
import com.yuzhitong.shapi.presenter.StartPresenter;
import com.yuzhitong.shapi.util.AdUtilManage;
import com.yuzhitong.shapi.util.LoggerUtil;
import com.yuzhitong.shapi.util.TTAdManagerHolder;
import com.yuzhitong.shapi.widget.AgreementConfigDialog;
import com.yuzhitong.shapi.widget.AgreementDialog;

public class MainActivity extends BaseMvpActivity<StartPresenter> implements StartContract.View {
    private final int successNumberAll = 2;

    private LinearLayout llIconBox;
    private long blackTime = 0;
    private RelativeLayout rlSplashBox;

    private int successNumber = 0;

    private Handler handler;
    private Runnable autoToHome;

    private boolean isOpenPrivateDialog;
    private boolean inPrivateWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    @Override
    protected void initPresenter() {
        presenter = new StartPresenter();
        presenter.attachView(this);
    }

    private void initView() {
        setDarkStatus();
        handler = new Handler(getMainLooper());
        llIconBox = (LinearLayout) findViewById(R.id.ll_icon_box);

        rlSplashBox = findViewById(R.id.rl_splash_box);

        if (isProxy()) {
            Toast.makeText(this, "网络错误", Toast.LENGTH_SHORT).show();
            return;
        }


        if (MyApplication.isAgree()) {
            loadNetData();
            startTimeout();
        } else {
            isOpenPrivateDialog = true;
            AgreementDialog agreementDialog = new AgreementDialog(this);
            agreementDialog.setOnClickBtnListener(new AgreementDialog.OnClickBtnListener() {
                @Override
                public void onDismiss() {
                    showAgreementAgain(1);
                }

                @Override
                public void onConfirm() {
                    loadNetData();
                    isOpenPrivateDialog = false;
                    if (permissionAgree()) {
                        Toast.makeText(MainActivity.this, "正在初始化数据,可能需要几秒时间", Toast.LENGTH_LONG).show();
                        showLoading();
                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this, needPermissions, REQUEST_PERMISSION_CODE);
                    }

                    initKSSDK(getApplicationContext());
                    //友盟正式初始化
                    UMConfigure.preInit(MainActivity.this, Contents.YM_SDK_ID, BuildConfig.CHANNEL_NAME);
                    UMConfigure.init(getApplicationContext(), Contents.YM_SDK_ID, BuildConfig.CHANNEL_NAME, UMConfigure.DEVICE_TYPE_PHONE, "");
                    TTAdManagerHolder.get().init(getApplicationContext(), new TTAdSdk.InitCallback() {
                        @Override
                        public void success() {
                            LoggerUtil.i("穿山甲SDK初始化成功");
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    startTimeout(10000);
                                }
                            }, 1000);
                        }

                        @Override
                        public void fail(int i, String s) {
                            LoggerUtil.i("穿山甲SDK初始化失败");
                        }
                    });
                    MyApplication.initDpSdk();
                    MyApplication.initBookDpSdk();
                }
            });
            agreementDialog.show();
        }

        handler.postDelayed(autoToHome = new Runnable() {
            @Override
            public void run() {
                if (!isOpenPrivateDialog) {
                    gotoHome();
                }
            }
        }, 7000);

    }


    private void showAgreementAgain(int degree) {
        AgreementConfigDialog agreementDialog = new AgreementConfigDialog(this, degree);
        agreementDialog.setOnClickBtnListener(new AgreementConfigDialog.OnClickBtnListener() {
            @Override
            public void onDismiss() {
                if(degree < 0) {
                    finish();
                    return;
                }
                showAgreementAgain(-1);
            }

            @Override
            public void onConfirm() {
                loadNetData();
                isOpenPrivateDialog = false;
                if (permissionAgree()) {
                    startTimeout(1000);
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this, needPermissions, REQUEST_PERMISSION_CODE);
                }
                //友盟正式初始化
                UMConfigure.init(getApplicationContext(), Contents.YM_SDK_ID, BuildConfig.CHANNEL_NAME, UMConfigure.DEVICE_TYPE_PHONE, "");
                TTAdManagerHolder.get().init(getApplicationContext(), new TTAdSdk.InitCallback() {
                    @Override
                    public void success() {
                        LoggerUtil.i("穿山甲SDK初始化成功");
                    }

                    @Override
                    public void fail(int i, String s) {
                        LoggerUtil.i("穿山甲SDK初始化失败");
                    }
                });
                MyApplication.initDpSdk();
                MyApplication.initBookDpSdk();
            }
        });
        agreementDialog.show();
    }

    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacks(autoToHome);
        }
        super.onDestroy();
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
    }

    private void startTimeout() {
        startTimeout(3000);
    }

    private void startTimeout(int timeout) {
        AdUtilManage.initShowSplash(this, rlSplashBox, Contents.AD_TT_SDK_PLASH, new AdUtilManage.GotoHomeListener() {
            @Override
            public void showSuccess() {
                llIconBox.setVisibility(View.GONE);
                if (handler != null) {
                    handler.removeCallbacks(autoToHome);
                }
            }

            @Override
            public void gotoHome() {
                successNumber++;
                if (successNumber >= successNumberAll) {
                    MainActivity.this.gotoHome();
                }
            }
        },
        new TTSplashAd.AdInteractionListener() {
            @Override
            public void onAdClicked(View view, int i) {

            }

            @Override
            public void onAdShow(View view, int i) {
                LoggerUtil.e("广告展示");
            }

            @Override
            public void onAdSkip() {
                gotoHome();
            }

            @Override
            public void onAdTimeOver() {
                gotoHome();
            }
        });
        //        Handler handler = new Handler(getMainLooper());
        //        handler.postDelayed(new Runnable() {
        //            @Override
        //            public void run() {
        //                gotoHome();
        //            }
        //        }, timeout);
    }

    private void gotoHome() {
        if (isOpenPrivateDialog) {
            return;
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
            }
        }, 1000);
    }

    /**
     * 是否授权 必要权限
     */
    private boolean permissionAgree() {
        return PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.ACCESS_NETWORK_STATE)
                && PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.ACCESS_WIFI_STATE)
                && PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.READ_PHONE_STATE);
    }


    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - blackTime > 2000) {
            blackTime = System.currentTimeMillis();
            Toast.makeText(this, getResources().getString(R.string.back_hint), Toast.LENGTH_SHORT).show();
            return;
        }
        super.onBackPressed();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_PERMISSION_CODE) {
            boolean isAgree = true;
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    //已授权
                    isAgree = false;
                }

            }
            if (!isAgree) {
                Toast.makeText(this, "未获取到权限，可能造成应用不稳定影响您的使用体验", Toast.LENGTH_SHORT).show();
            }
            startTimeout(1000);
        }
    }

    public void initKSSDK(Context appContext) {
        KsAdSDK.init(appContext, new SdkConfig.Builder()
                .appId(Contents.KS_SDK_APP_ID) // 测试aapId，请联系快⼿平台申请正式AppId，必填
                .appName(getString(R.string.app_name)) // 测试appName，请填写您应⽤的名称，⾮必填
                .showNotification(true) // 是否展示下载通知栏
                .debug(BuildConfig.DEBUG) // 是否开启sdk 调试⽇志 可选
                .build());
    }

    @Override
    public void result() {
        presenter.getAdState();
    }


    private void loadNetData(){
        presenter.getUrl();
    }

    @Override
    public void initSuccess() {
        successNumber++;
        if (successNumber >= successNumberAll && isOpenPrivateDialog) {
            gotoHome();
        }
    }


}